package cn.weblog.api.controller;

import cn.weblog.api.domain.User;
import cn.weblog.api.domain.vo.Password;
import cn.weblog.api.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
@ResponseBody
public class LoginController {

	@Autowired
	private UserService userService;

/*	@GetMapping({"","/"})
	public String loginPage(HttpSession session){
		if (session.getAttribute("user") == null) {
			return "user/login";    //用户没有登录，或者登录已经失效
		}
		return "user/personal";
	}*/

	/*为了方便测试，使用以下代码*/
	/*------------------------------------------------------------*/

/*	@Autowired
	private PassageService passageService;

	@Autowired
	private CatagoryService catagoryService;

	@GetMapping({"","/"})
	public String loginPage(HttpSession session, Model model){
		User user = userService.findByUserId(1001);
		session.setAttribute("user",user);
		return "user/personal";
	}*/

	/*------------------------------------------------------------*/

	@PostMapping("change/{userId}")//t 修改密码
	String change(@RequestBody Password password, @PathVariable Integer userId){
		Map<String,Object> result=new HashMap<>();
		int i = userService.findPassword(userId, password.getPassword());
		if(i!=1){
			result.put("Msg","原先密码输入不正确");
			return JSON.toJSONString(result);
		}else{
			i=userService.changePassage(userId,password.getNewPass());
			if(i==1){
				//result.put("Msg","修改成功");
				// 没有提示信息
				return JSON.toJSONString(result);
			}
		}
		result.put("Msg","修改失败");
		return JSON.toJSONString(result);
	}

	@PostMapping("login")//t
	//获取页面表单中name为userId和password的输入框值
	String login(@RequestBody User user){
		User u = userService.login(user.getUserId(), user.getPassword());
		Map<String,Object> result=new HashMap<>();
		if (u==null){
			result.put("Msg","账号或密码输入错误");
			return JSON.toJSONString(result);
		}
		// 没有msg表示登陆成功
		result.put("user",u);
		return JSON.toJSONString(result);
	}

/*	@GetMapping("/logout")
	String logout(HttpSession session){
		session.removeAttribute("user");
		return "redirect:/user";		//用户界面：及登陆页面
	}*/
}
